package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.dto.ThirdInfoDTO;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.LogFactory;
import com.block.common.service.merchant.IMerchantThirdBaseInfoService;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApi2Service;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.HaoHanYouJieSsqUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantThirdBaseInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 *  浩瀚有借全授权
 */
@Service
public class HaoHanYouJieApiService implements IPushApiService, IPushApi2Service {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMerchantThirdBaseInfoService merchantThirdBaseInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();

        Map<String, Object> paramMap = new HashMap<>();

        paramMap.put("name_md5", SecureUtil.md5(memberSourceInfo.getRealname()));
        paramMap.put("idno_md5", SecureUtil.md5(memberSourceInfo.getIdcard()));
        paramMap.put("phone_md5", memberSourceInfo.getMobileMd5());
        paramMap.put("age",String.valueOf(memberSourceInfo.getAge()));
        if (memberSourceInfo.getSex() == 1){
            paramMap.put("sex", "男");
        }else {
            paramMap.put("sex", "女");
        }

        if (StringUtils.isNotEmpty(memberSourceInfo.getReqIp())){
            paramMap.put("ip", memberSourceInfo.getReqIp());
        }else {
            paramMap.put("ip", "127.0.0.1");
        }

        StringBuilder stringBuilder = new StringBuilder();
        String provinceCity = stringBuilder.append(memberSourceInfo.getProvince()).append("/").append(memberSourceInfo.getCity()).toString();
        paramMap.put("working_city",provinceCity);

        paramMap.put("salary_type","银行代发");

        paramMap.put("loan_amount", HaoHanYouJieSsqUtil.getloan(memberSourceInfo.getLoanAmount()));
        paramMap.put("loan_period", HaoHanYouJieSsqUtil.getloanTime(memberSourceInfo.getLoanTime()));
        paramMap.put("reserved_funds",HaoHanYouJieSsqUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("social_security",HaoHanYouJieSsqUtil.getshebao(memberSourceInfo.getShebao()));
        paramMap.put("credit_record",HaoHanYouJieSsqUtil.getyuqi(memberSourceInfo.getYuqi()));
        paramMap.put("insurance",HaoHanYouJieSsqUtil.getbaoxian(memberSourceInfo.getBaoxian()));
        paramMap.put("real_estate",HaoHanYouJieSsqUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("zhima",HaoHanYouJieSsqUtil.getzhima(memberSourceInfo.getZhima()));
        paramMap.put("car",HaoHanYouJieSsqUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("industry",HaoHanYouJieSsqUtil.getJob(memberSourceInfo.getGongzuo()));
        paramMap.put("loan_lately", "没有申请过贷款");
        paramMap.put("phone_pre", memberSourceInfo.getMobile().substring(0,3));


        log.info("【浩瀚有借全流程导量】 撞库开始【infoId】{}【infoName】{}【queryUrl】{}【paramMap】{}【bizMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【浩瀚有借全流程导量】撞库结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer respCode = resultObject.getInteger("code");
        String respMsg = resultObject.getString("msg");

        pushApiResult.setCode(String.valueOf(respCode));
        pushApiResult.setMessage(respMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (respCode != 0) {
            pushApiResult.setPushSuccess(false);
            return pushApiResult;
        }
        String tid = resultObject.getString("tid");

        // 撞库成功之后，商户的机构数据存储
        JSONArray jsonObject2 = resultObject.getJSONArray("list");
        JSONObject data = jsonObject2.getJSONObject(0);

        String serialNo = tid;
        String logo = data.getString("logo");
        String name = data.getString("product_name");
        String institutionName = data.getString("company_name");
        JSONArray protocols = data.getJSONArray("protocols");
        JSONObject jsonObject1 = protocols.getJSONObject(0);
        // 撞库成功之后，商户的机构数据存储

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
        thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
        thirdInfoDTO.setOrderNo(orderNo);
        JSONObject infoObject = new JSONObject();
        infoObject.put("orderNo",serialNo);
        infoObject.put("productId",serialNo);
        infoObject.put("productName",name);
        infoObject.put("companyName",institutionName);
        infoObject.put("companyLogo",logo);
        infoObject.put("maxLoanAmount","200000");
        infoObject.put("maxLoanRate","24");
        infoObject.put("minLoanRate","1");
        infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("protocalName",jsonObject1.getString("label"));
        jsonObject.put("protocalUrl",jsonObject1.getString("value"));
        jsonArray.add(jsonObject);
        infoObject.put("protocalList",jsonArray);
        thirdInfoDTO.setInfoObject(infoObject);

        //进行分润操作
        String priceType = pushApiKeyParam.getPriceType();
        BigDecimal typeRate = pushApiKeyParam.getTypeRate();
        if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
            BigDecimal price = data.getBigDecimal("price");//下游返回分润后价格
            if (price.compareTo(new BigDecimal(0.00)) == -1){
                pushApiResult.setPushSuccess(false);
                return pushApiResult;
            }
            BigDecimal priceRight = typeRate.multiply(price);//分润后价格
            pushApiResult.setPrice(price);
            pushApiResult.setPriceRight(priceRight);
        }

        boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
        if (save){
            pushApiResult.setPushSuccess(true);
            pushApiResult.setOutOrderNo(serialNo);
            extJson.put("tid", serialNo);
        }else{
            pushApiResult.setMessage("保存撞库数据失败");
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        JSONObject bizMap = new JSONObject();

        String tid = extJson.getString("tid");
        bizMap.put("uuid",tid);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("phone",memberSourceInfo.getMobile());
        jsonObject.put("name",memberSourceInfo.getRealname());
        jsonObject.put("idno",memberSourceInfo.getIdcard());
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime = LocalDateTime.now();
        String formattedDateTime = dateTime.format(formatter);
        jsonObject.put("authorize_time",formattedDateTime);
        JSONArray jsonArray = new JSONArray();
        MerchantThirdBaseInfo merchantThirdBaseInfo = merchantThirdBaseInfoService.selectEntityByOrderNo(orderNo);
        if (ObjectUtil.isEmpty(merchantThirdBaseInfo)){
            pushApiResult.setMessage("商户机构数据为空【pushId】" + orderNo);
            return pushApiResult;
        }

        String orderId = extJson.getString("orderId");
        String orderItemId = extJson.getString("orderItemId");
        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), orderId, orderItemId);
        jsonArray.add(protocolUrl);
        jsonObject.put("authorize",jsonArray);
        bizMap.put("thirdInfo",jsonObject);

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        log.info("【浩瀚有借全流程导量】导单开始【infoId】{}【infoName】{}【queryUrl】{}【bizMap】{}【paramMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), requestUrl, JSON.toJSONString(bizMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(bizMap))
                .execute().body();
        log.info("【浩瀚有借全流程导量】导单结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer respCode = resultObject.getInteger("code");
        String respMsg = resultObject.getString("msg");

        pushApiResult.setCode(String.valueOf(respCode));
        pushApiResult.setMessage(respMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setOrderNo(orderNo );
        thirdInfoDTO.setRetCode(String.valueOf(respCode));
        thirdInfoDTO.setRetMsg(respMsg);
        thirdInfoDTO.setResultInfo(result);
        thirdInfoDTO.setStatus("FAILED");

        if (respCode == 0) {
            thirdInfoDTO.setStatus("SUCCESS");
        }
        merchantThirdBaseInfoService.updateThirdInfo(thirdInfoDTO);

        if (respCode == 0) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    @Override
    public PushApiResult checkUserCode(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();

        Map<String, Object> paramMap = new HashMap<>();

        paramMap.put("name_md5", SecureUtil.md5(memberSourceInfo.getRealname()));
        paramMap.put("idno_md5", SecureUtil.md5(memberSourceInfo.getIdcard()));
        paramMap.put("phone_md5", memberSourceInfo.getMobileMd5());
        paramMap.put("age",String.valueOf(memberSourceInfo.getAge()));
        if (memberSourceInfo.getSex() == 1){
            paramMap.put("sex", "男");
        }else {
            paramMap.put("sex", "女");
        }

        if (StringUtils.isNotEmpty(memberSourceInfo.getReqIp())){
            paramMap.put("ip", memberSourceInfo.getReqIp());
        }else {
            paramMap.put("ip", "127.0.0.1");
        }

        StringBuilder stringBuilder = new StringBuilder();
        String provinceCity = stringBuilder.append(memberSourceInfo.getProvince()).append("/").append(memberSourceInfo.getCity()).toString();
        paramMap.put("working_city",provinceCity);

        paramMap.put("salary_type","银行代发");

        paramMap.put("loan_amount", HaoHanYouJieSsqUtil.getloan(memberSourceInfo.getLoanAmount()));
        paramMap.put("loan_period", HaoHanYouJieSsqUtil.getloanTime(memberSourceInfo.getLoanTime()));
        paramMap.put("reserved_funds",HaoHanYouJieSsqUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("social_security",HaoHanYouJieSsqUtil.getshebao(memberSourceInfo.getShebao()));
        paramMap.put("credit_record",HaoHanYouJieSsqUtil.getyuqi(memberSourceInfo.getYuqi()));
        paramMap.put("insurance",HaoHanYouJieSsqUtil.getbaoxian(memberSourceInfo.getBaoxian()));
        paramMap.put("real_estate",HaoHanYouJieSsqUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("zhima",HaoHanYouJieSsqUtil.getzhima(memberSourceInfo.getZhima()));
        paramMap.put("car",HaoHanYouJieSsqUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("industry",HaoHanYouJieSsqUtil.getJob(memberSourceInfo.getGongzuo()));
        paramMap.put("loan_lately", "没有申请过贷款");
        paramMap.put("phone_pre", memberSourceInfo.getMobile().substring(0,3));


        log.info("【上游浩瀚有借全流程导量】 撞库开始【infoId】{}【infoName】{}【queryUrl】{}【paramMap】{}【bizMap】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【上游浩瀚有借全流程导量】撞库结束【infoId】{}【infoName】{}【result】{}",
                pushApiKeyParam.getInfoId(), pushApiKeyParam.getInfoName(), result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer respCode = resultObject.getInteger("code");
        String respMsg = resultObject.getString("msg");

        pushApiResult.setCode(String.valueOf(respCode));
        pushApiResult.setMessage(respMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (respCode != 0) {
            pushApiResult.setPushSuccess(false);
            return pushApiResult;
        }
        String tid = resultObject.getString("tid");

        // 撞库成功之后，商户的机构数据存储
        JSONArray jsonObject2 = resultObject.getJSONArray("list");
        JSONObject data = jsonObject2.getJSONObject(0);

        String serialNo = tid;
        String logo = data.getString("logo");
        String name = data.getString("product_name");
        String institutionName = data.getString("company_name");
        JSONArray protocols = data.getJSONArray("protocols");
        JSONObject jsonObject1 = protocols.getJSONObject(0);
        // 撞库成功之后，商户的机构数据存储

        ThirdInfoDTO thirdInfoDTO = new ThirdInfoDTO();
        thirdInfoDTO.setInfoId(Integer.valueOf(pushApiKeyParam.getInfoId()));
        thirdInfoDTO.setInfoName(pushApiKeyParam.getInfoName());
        thirdInfoDTO.setOrderNo(orderNo);
        JSONObject infoObject = new JSONObject();
        infoObject.put("orderNo",serialNo);
        infoObject.put("productId",serialNo);
        infoObject.put("productName",name);
        infoObject.put("companyName",institutionName);
        infoObject.put("companyLogo",logo);
        infoObject.put("maxLoanAmount","200000");
        infoObject.put("maxLoanRate","24");
        infoObject.put("minLoanRate","1");
        infoObject.put("businessInfo",pushApiKeyParam.getInfoName());
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("protocalName",jsonObject1.getString("label"));
        jsonObject.put("protocalUrl",jsonObject1.getString("value"));
        jsonArray.add(jsonObject);
        infoObject.put("protocalList",jsonArray);
        thirdInfoDTO.setInfoObject(infoObject);

        //进行分润操作
        String priceType = pushApiKeyParam.getPriceType();
        BigDecimal typeRate = pushApiKeyParam.getTypeRate();
        if (ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
            BigDecimal price = data.getBigDecimal("price");//下游返回分润后价格
            if (price.compareTo(new BigDecimal(0.00)) == -1){
                pushApiResult.setPushSuccess(false);
                return pushApiResult;
            }
            BigDecimal priceRight = typeRate.multiply(price);//分润后价格
            pushApiResult.setPrice(price);
            pushApiResult.setPriceRight(priceRight);
        }

        boolean save = merchantThirdBaseInfoService.saveThirdInfo(thirdInfoDTO);
        if (save){
            pushApiResult.setPushSuccess(true);
            pushApiResult.setOutOrderNo(serialNo);
            extJson.put("tid", serialNo);
        }else{
            pushApiResult.setMessage("保存撞库数据失败");
        }
        return pushApiResult;
    }
}
